﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using FileHelpers;
using Model;
using Model.Static;

namespace Command.Commands
{
	public class SyncAchievementsCommand : BaseCommand<Options>
	{
		private readonly IRepository _repository;

		public SyncAchievementsCommand(IRepository repository)
		{
			_repository = repository;
		}

		protected override void InternalExecute(Options options)
		{
			var file = Path.Combine(Environment.CurrentDirectory, "Static\\Data\\Achievement.csv");
			var rows = new FileHelperEngine<AchievementRecord> {Options = {IgnoreFirstLines = 1}}
				.ReadFile(file)
				.OrderBy(x => x.ParentExternalKey)
				.ThenBy(x => x.ExternalKey)
				.ToArray();
			foreach (var row in rows)
			{
				var theRow = row;
				var achievement = _repository.Query<Achievement>().FirstOrDefault(x => x.ExternalKey == theRow.ExternalKey);
				if (achievement == null)
				{
					achievement = new Achievement
					{
						ExternalKey = theRow.ExternalKey,
						Title = theRow.Name,
						Description = theRow.Description,
						Category = _repository.Query<AchievementCategory>().FirstOrDefault(x => x.ExternalKey == theRow.ExternalCategoryKey),
						Faction = theRow.Faction == 0 ? Faction.Horde : theRow.Faction == 1 ? Faction.Alliance : Faction.Neutral,
						Points = theRow.Points,
						Previous = _repository.Query<Achievement>().FirstOrDefault(x => x.ExternalKey == theRow.ParentExternalKey)
					};
					Console.WriteLine("Creating Missing Achievement: {0}", achievement.Title);
					_repository.Save(achievement);
				}
			}
		}
	}
}
